package com.globant.dashboard.persist;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;

import com.globant.dashboard.model.User;

public class UserValidator {
	
	@Autowired
	private UserDAO userDAO;
	
	public UserValidator(){
		
	}

	private final int MAXEMAIL=60;
	
	public boolean emailValidator(User user) {

		boolean validEmail;
		
		// Input the string for validation
		String email = user.getEmail();
		char[] array;		
		
		//Convert the string to an Array
		array = email.toCharArray();
		
		int count=0, i=0;
		boolean valid;

		// Set the email pattern string
		Pattern p = Pattern.compile("^[\\w._-]+?@[\\w._-]+?(\\.(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum))(.(\\w){2}+)?$");
		
		// Match the given string with the pattern
		Matcher m = p.matcher(email);
		
			//Validate if before the '@' there are less than, or 60 characters
			while(array[i] != '@' && i<array.length){
				count++;
				i++;
			}	
			
			if(count<=MAXEMAIL){
				valid=true;
			} else {
				valid=false;
			}
			
			
		//Validate if the e-mail is correct

		if (m.matches() && valid) {
			validEmail = true;
		} else {
			validEmail = false;
		}

		return validEmail;
	}
	
	public boolean nameValidator(User user) {

		boolean validName;
		
		// Input the string for validation
		String name = user.getName();
		Pattern p = Pattern.compile("^[A-Za-z-\\s]*$");
		Matcher m = p.matcher(name);
		System.out.println(m.matches());
		//Valid if the name is not numeric
		if ((!isNumeric(name)) && m.matches() && name.length()<=50 && !("".equals(name))){ 
			validName = true;				
		} else {		  
			validName = false;
		}
		System.out.println(validName);
		return validName;
	}
	
	public boolean isNewUser(String email){
		User result = userDAO.getByEmail(email);
		if(result == null){
			return true;
		}else{
			return false;
		}
		
	}
	
	private boolean isNumeric(String s){
	    try{
	        Integer.parseInt(s);
	        return true;
	    }
	    catch( NumberFormatException err ){
	        return false;
	    }
	}

}
